#include "proto.h"

int main (void)
{
	struct sockaddr_in cli_addr;
	struct ip_mreqn imr;
	struct msg_t buf;

	int fd = socket (AF_INET, SOCK_DGRAM, 0);
	if (-1 == fd) {
		perror ("socket ()");
		exit (1);
	}

	cli_addr.sin_family = AF_INET;
	cli_addr.sin_port = htons (atoi(RCV_PORT));
	inet_aton (GROUP_IP, &cli_addr.sin_addr);
	int b = bind (fd, (struct sockaddr *)&cli_addr, sizeof(cli_addr));
	if (-1 == b) {
		perror ("bind()");
		goto ERROR;
	}
	//加入多播组
	inet_aton (GROUP_IP, &imr.imr_multiaddr);
	inet_aton ("0.0.0.0", &imr.imr_address);
	imr.imr_ifindex = if_nametoindex ("ens33");
	if (-1 == setsockopt (fd, IPPROTO_IP, IP_ADD_SOURCE_MEMBERSHIP, &imr, sizeof (imr)))
	{
		perror ("setscokopt()");
		return -1;
	}

	while (1) {
		//从多播组中接受数据
		bzero (&buf, MAGSIZE);
		recvfrom (fd, &buf, MAGSIZE, 0, NULL, NULL);
		puts (buf.str);
		sleep (1);
	}
	close (fd);
	return 0;
ERROR:
	close (fd);
}
